package com.org.fileUpload;

import com.org.exception.BaseException;
import com.org.message.BaseMessage;
import com.org.properties.RedisKeyPropertis;
import com.org.result.Result;
import com.org.vo.UploadVO;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RestController
public class FileUpload {

    @Autowired
    private FileStorageService fileStorageService;//注入实列
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 上传文件，成功返回文件 url
     */
    @PostMapping("/upload")
    public Result<UploadVO> upload2(MultipartFile file) {
        //定义文件存储路径
        String filePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
        FileInfo fileInfo = fileStorageService.of(file)
                .setPath(filePath) //保存到相对路径下
                .upload();  //将文件上传到对应地方
        //判断是否上传成功
        if(fileInfo == null) {
            throw new BaseException(BaseMessage.UPLOAD_ERROR);
        }else{
            //存入Redis用于后续删除垃圾文件
            stringRedisTemplate.opsForSet().add(RedisKeyPropertis.REDIS_KEY_UP_ALL, fileInfo.getUrl());
        }
        UploadVO upLoad = new UploadVO();
        upLoad.setUrl(fileInfo.getUrl());
        return Result.success(upLoad);
    }

}
